package com.hy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.hy.base.BaseInfoProperties;
import com.hy.enums.YesOrNo;
import com.hy.grace.result.GraceJSONResult;
import com.hy.mapper.QuestionLibMapper;
import com.hy.mapper.QuestionLibMapperCustom;
import com.hy.pojo.Job;
import com.hy.pojo.QuestionLib;
import com.hy.pojo.bo.QuestionLibBO;
import com.hy.pojo.vo.InitQuestionsVO;
import com.hy.pojo.vo.QuestionLibVO;
import com.hy.service.CandidateService;
import com.hy.service.JobService;
import com.hy.service.QuestionLibService;
import com.hy.utils.PagedGridResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class QuestionLibServiceImpl extends BaseInfoProperties implements QuestionLibService {

    @Autowired
    private QuestionLibMapper questionLibMapper;
    @Autowired
    private QuestionLibMapperCustom questionLibMapperCustom;
    @Autowired
    private CandidateService candidateService;
    @Autowired
    private JobService jobService;


    /**
     * 创建或更新面试题
     * @param questionLibBO
     */
    @Override
    public void createOrUpdate(QuestionLibBO questionLibBO) {

        QuestionLib questionLib = new QuestionLib();
        BeanUtils.copyProperties(questionLibBO, questionLib);
        questionLib.setUpdatedTime(LocalDateTime.now());

        if (StringUtils.isBlank(questionLibBO.getId())) {
            // 创建
            questionLib.setIsOn(YesOrNo.YES.type);
            questionLib.setCreateTime(LocalDateTime.now());
            questionLibMapper.insert(questionLib);
        } else {
            // 更新
            questionLibMapper.updateById(questionLib);
        }
    }

    /**
     * 查询面试题列表
     * @param aiName
     * @param question
     * @param page
     * @param pageSize
     */
    @Override
    public PagedGridResult queryList(String aiName, String question, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        Map<String, Object> map = new HashMap<>();

        if (StringUtils.isNotBlank(aiName)) {
            map.put("aiName", aiName);
        }
        if (StringUtils.isNotBlank(question)) {
            map.put("question", question);
        }
        List<QuestionLibVO> questionLibList = questionLibMapperCustom.queryQuestionLibList(map);

        return setterPagedGrid(questionLibList, page);
    }

    /**
     * 设置面试题是否启用或禁用
     * @param questionLibId
     * @param isOn
     */
    @Override
//    @Transactional
    public void setDisplayOrNot(String questionLibId, Integer isOn) {

        QuestionLib questionLib = new QuestionLib();
        questionLib.setId(questionLibId);
        questionLib.setIsOn(isOn);
        questionLib.setUpdatedTime(LocalDateTime.now());

        questionLibMapper.updateById(questionLib);
    }

    /**
     * 删除面试题
     * @param questionLibId
     */
    @Override
    public void delete(String questionLibId) {
        questionLibMapper.deleteById(questionLibId);
    }

    @Override
    public boolean isQuestionContainInterviewer(String interviewerId) {
        // 构造查询条件，根据面试官ID查询职位记录
        QueryWrapper<QuestionLib> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("interviewer_id", interviewerId);

        // 查询匹配条件的职位记录数量
        Long count = questionLibMapper.selectCount(queryWrapper);

        // 根据记录数量判断是否包含该面试官
        return count > 0 ? true : false;
    }

    /**
     * 随机获取面试题
     * @param candidateId
     * @param questionNum
     * @return
     */
    @Override
    public List<InitQuestionsVO> getRandomQuestions(String candidateId, Integer questionNum) {

        // 1.获得负责面试应聘者的面试官ID
        String jobId = candidateService.getDetail(candidateId).getJobId();
        String interviewerId = jobService.getDetails(jobId).getInterviewerId();

        // 2.根据面试官ID获得其所负责的所有面试题
        Long count = questionLibMapper.selectCount(
                new QueryWrapper<QuestionLib>().eq("interviewer_id", interviewerId)
        );

        // 3.随机获取指定数量的面试题
        List<Long> randomQuestionIds = new ArrayList<>();
        for (int i = 0; i < questionNum; i++) {
            Random random = new Random();
            long randomNum = random.nextLong(count);
            if ( !randomQuestionIds.contains(randomNum) ){
                // randomQuestionIds中不包含该数字，则添加
                randomQuestionIds.add(randomNum);
            }else{
                // 随机数已存在，则重新生成
                i--;
            }
        }

        // 4.根据索引下面从数据库获得面试题
        List<InitQuestionsVO> questionList = new ArrayList<>();
        for (Long randomQuestionId : randomQuestionIds) {
            Map<String, Object> map = new HashMap<>();
            map.put("randomQuestionId", randomQuestionId);

            InitQuestionsVO question = questionLibMapperCustom.queryInitQuestion(map);

            questionList.add(question);
        }
        return questionList;
    }
}
